import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { SalesmanService } from '@core/routes-services/salesman.service';
import { mobileValidate } from '@core/util/formControl-validate-utils';

@Component({
  selector: 'app-salesman-form',
  templateUrl: './salesman-form.component.html',
})
export class SalesmanFormComponent implements OnInit {
  @Input() entity: any = {};
  @Input() isModel: boolean = true;
  validateForm: FormGroup;
  isLoading: boolean = false;
  @Output() finish = new EventEmitter();

  @Input() districtOption: any [] = [];
  @Input() salesManTypeOption: any [] = [];

  constructor(
    private fb: FormBuilder,
    private salesmanService: SalesmanService,
    public message: NzMessageService,
  ) {
  }

  ngOnInit() {
    this.districtOption = this.districtOption.filter((d) => d.status != 2);
    this.initValidateForm();
  }


  initValidateForm() {
    //角色: 1-业务员，2-渠道商，3-门店，4-代理
    if (this.entity.role == 4 || this.entity.role == 3) {
      this.validateForm = this.fb.group({
        shopName: [this.entity.shopName, [Validators.required, Validators.maxLength(30)]],
        address: [this.entity.address, [Validators.required, Validators.maxLength(100)]],
        typeId: [this.entity.typeId, [Validators.required]],
        name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
        phone: [this.entity.phone, [Validators.required, mobileValidate]],
        idNumber: [this.entity.idNumber, [Validators.required]],
        districtId: [this.entity.districtId, [Validators.required]],
      });
    } else {
      this.validateForm = this.fb.group({
        name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
        phone: [this.entity.phone, [Validators.required, mobileValidate]],
        idNumber: [this.entity.idNumber, [Validators.required]],
        districtId: [this.entity.districtId, [Validators.required]],
      });
    }
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.salesmanService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.finish.emit(res.data);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.finish.emit(false);
  }

}
